package com.tianji.remark.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tianji.api.dto.msg.LikedTimesDTO;
import com.tianji.common.autoconfigure.mq.RabbitMqHelper;
import com.tianji.common.constants.MqConstants;
import com.tianji.common.utils.CollUtils;
import com.tianji.common.utils.StringUtils;
import com.tianji.common.utils.UserContext;
import com.tianji.remark.constants.RedisConstants;
import com.tianji.remark.domain.dto.LikeRecordFormDTO;
import com.tianji.remark.domain.po.LikedRecord;
import com.tianji.remark.mapper.LikedRecordMapper;
import com.tianji.remark.service.ILikedRecordService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.connection.StringRedisConnection;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

/**
 * <p>
 * 点赞记录表 服务实现类
 * </p>
 *
 * @author 晚风
 * @since 2023-09-24
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class LikedRecordRedisServiceImpl extends ServiceImpl<LikedRecordMapper, LikedRecord> implements ILikedRecordService {

    private final RabbitMqHelper rabbitMqHelper;
    private final StringRedisTemplate redisTemplate;

    @Override
    public void addLikeRecord(LikeRecordFormDTO dto) {
        // 1. 获取当前用户id
        Long userId = UserContext.getUser();
        // 2. 判断是否点赞 liked为true表示点赞
//        boolean flag = true;
//        if (dto.getLiked()){
//            // 2.1. 点赞逻辑
//            flag = liked(dto);
//        }else {
//            // 2.2. 取消点赞
//            flag = unliked(dto);
//        }
        boolean flag = dto.getLiked() ? liked(dto,userId) : unliked(dto,userId);
        if (!flag){
            return;
        }
        // 3. 根据业务id统计点赞数量
       // Integer totalLikedNum = this.lambdaQuery().eq(LikedRecord::getBizId, dto.getBizId()).count();
        // 使用redis统计 业务id的总点赞量
        String key = RedisConstants.LIKE_BIZ_KEY_PREFIX + dto.getBizId();
        Long totalLikedNum = redisTemplate.opsForSet().size(key);
        if (totalLikedNum == null){
            return;
        }
        // 4. 使用MQ发送消息
/*        String routingKey = StringUtils.format(MqConstants.Key.LIKED_TIMES_KEY_TEMPLATE, dto.getBizType());
        LikedTimesDTO msg = new LikedTimesDTO();
        msg.setLikedTimes(totalLikedNum);
        msg.setBizId(dto.getBizId());
        rabbitMqHelper.send(
                MqConstants.Exchange.LIKE_RECORD_EXCHANGE,
                routingKey,
                msg
                );*/
        //采用zset结构缓存点赞的总数
        String bizTypeTotalLikeKey = RedisConstants.LIKE_COUNT_KEY_PREFIX + dto.getBizType();
        redisTemplate.opsForZSet().add(bizTypeTotalLikeKey,dto.getBizId().toString(),totalLikedNum);
    }

    @Override
    public Set<Long> getLikesStatusByBizIds(List<Long> bizIds) {
        // 1. 获取用户
/*        Long userId = UserContext.getUser();
        if (CollUtils.isEmpty(bizIds)){
            return CollUtils.emptySet();
        }
        Set<Long> likedBizIds = new HashSet<>();
        // 2. 循环bizIds
        for (Long bizId : bizIds) {
            Boolean member = redisTemplate.opsForSet().isMember(RedisConstants.LIKE_COUNT_KEY_PREFIX + bizId, userId.toString());
            if (member){
                // 3. 判断当前业务, 当前用户是否点赞  如果有当前用户id则存入新集合返 回
                likedBizIds.add(userId);
            }
        }
                return likedBizIds;
        */

/*        // 1. 获取用户id
        Long userId = UserContext.getUser();
        // 2. 查询点赞记录表
        List<LikedRecord> likedRecords = this.lambdaQuery().in(LikedRecord::getBizId, bizIds).eq(LikedRecord::getUserId, userId).list();
        Set<Long> likedBizIds = likedRecords.stream().map(LikedRecord::getBizId).collect(Collectors.toSet());*/
        Long userId = UserContext.getUser();
        // 查询点赞状态
        List<Object> objects = redisTemplate.executePipelined((RedisCallback<Object>) connection ->{
            StringRedisConnection src = (StringRedisConnection) connection;
            for (Long bizId : bizIds){
                String key = RedisConstants.LIKE_BIZ_KEY_PREFIX + bizId;
                src.sIsMember(key,userId.toString());
            }
            return null;
        });
        // 返回数据
        return IntStream.range(0,objects.size()) // 创建从0到集合size的流
                .filter(i ->(boolean) objects.get(i)) // 遍历每个元素 保留结果为true的角标i
                .mapToObj(bizIds::get)// 用角标i取bizIds中的对应数据, 就是点过赞的
                .collect(Collectors.toSet()); // 收集
    }

    @Override
    public void readLikedTimesAndSendMessage(String bizType, int maxBizSize) {
        // 1. 拼接key
        String bizTypeTotalLikeKey = RedisConstants.LIKE_COUNT_KEY_PREFIX + bizType;
        // 2. 从redis的zset结构中取maxBizSize 的业务点赞信息  popmin
        Set<ZSetOperations.TypedTuple<String>> typedTuples = redisTemplate.opsForZSet().popMin(bizTypeTotalLikeKey, maxBizSize);
        List<LikedTimesDTO> list = new ArrayList<>();
        for (ZSetOperations.TypedTuple<String> typedTuple : typedTuples) {
            String bizId = typedTuple.getValue();
            Double likedTimes = typedTuple.getScore();
            if (StringUtils.isBlank(bizId) || likedTimes == null){
                continue;
            }
            // 3. 封装LikedTimesDTO 消息数据
            LikedTimesDTO timesDTO = new LikedTimesDTO();
            timesDTO.setBizId(Long.valueOf(bizId));
            timesDTO.setLikedTimes(likedTimes.intValue());
            list.add(timesDTO);
        }
        // 4. 发送消息到mq
        if (CollUtils.isNotEmpty(list)){
            log.info("批量发送消息");
            String routingKey = StringUtils.format(MqConstants.Key.LIKED_TIMES_KEY_TEMPLATE, bizType);
            rabbitMqHelper.send(
                    MqConstants.Exchange.LIKE_RECORD_EXCHANGE,
                    routingKey,
                    list);
        }

    }

    // 取消赞
    private boolean unliked(LikeRecordFormDTO dto, Long userId) {
//        LikedRecord record = this.lambdaQuery().eq(LikedRecord::getUserId, userId)
//                .eq(LikedRecord::getBizId, dto.getBizId())
//                .one();
//        if (record == null){
//            // 说明没有点过赞，取消失败
//            return false;
//        }
//        // 删除点赞数量
//        boolean result = this.removeById(record.getId());
//        return result;
        String key = RedisConstants.LIKE_BIZ_KEY_PREFIX + dto.getBizId();
        Long result = redisTemplate.opsForSet().remove(key, userId.toString());
        return result != null && result > 0;
    }
    // 点赞
    private boolean liked(LikeRecordFormDTO dto, Long userId) {
        // 基于redis做点赞
        String key = RedisConstants.LIKE_BIZ_KEY_PREFIX + dto.getBizId();
        Long result = redisTemplate.opsForSet().add(key, userId.toString());
        return result != null && result > 0;
    }
}
